﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;

namespace Hilteq.FetchXml
{
    public class FetchXmlQuery : CodeActivity
    {
        protected override void Execute(CodeActivityContext executionContext)
        {

            try
            {
                
                IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                ITracingService tracer = executionContext.GetExtension<ITracingService>();
                
                RowReturned.Set(executionContext, false);

                string fetch = FetchXML.Get<string>(executionContext);
                fetch = String.Format(fetch, context.PrimaryEntityId);
                
                if (service.RetrieveMultiple(new FetchExpression(fetch)).Entities.Count > 0)
                    RowReturned.Set(executionContext, true);


            }
            catch (Exception ex)
            {
                Helpers.Throw(String.Format("An error occurred in the {0} plug-in.",
                        this.GetType().ToString()),
                      ex);
            }


        }

        [Input("Fetch XML")]
        public InArgument<string> FetchXML { get; set; }

        [Output("RowFound")]
        public OutArgument<bool> RowReturned { get; set; }

    }

}
